<?php


namespace RedMVC\Form;
use RedMVC;

/**
 * FileHelper class
 *
 * @category    RedMVC
 * @package     Form
 * @author      Jan Fischer, bitWorking <info@bitworking.de>
 */
class FileHelper{

    protected function getError($error, $value = null){
        $translate = RedMVC\Registry::get('RedMVC_Translate');
        return sprintf($translate->_($error), $value);
    }

    public function copy(RedMVC\Form\Element\File $file, $onlyCheck = false){

        $varname = str_replace('[]', '', $file->getVarname());
        
        if(!isset($_FILES[$varname])){
            if($file->isRequired()){
                $file->addError($this->getError('FORM_FILE_NO_FILE'));
                return false;
            }
            return true;
        }
        else{
            $fileVar = $_FILES[$varname];            
            if(is_array($fileVar['name'])){
                $fileCount  = count($fileVar['name']);
                $fileAttr   = $file->getFile();
                if((null !== $fileAttr->maxFiles) && ($fileCount > $fileAttr->maxFiles)){
                    $file->addError($this->getError('FORM_FILE_TO_MANY_FILES', $fileAttr->maxFiles));
                    return false;
                }
                if((null !== $fileAttr->maxSizeTotal) && ($this->_getTotalSize($fileVar['size']) > $fileAttr->maxSizeTotal)){
                    $file->addError($this->getError('FORM_FILE_TOTAL_TO_LARGE', round($fileAttr->maxSizeTotal/1024/1024, 2)));
                    return false;
                }
                for($i=0;$i<$fileCount;$i++){
                    $success = $this->_copyFile(
                        $file,
                        $onlyCheck,
                        true,
                        $fileVar['name'][$i],
                        $fileVar['type'][$i],
                        $fileVar['tmp_name'][$i],
                        $fileVar['error'][$i],
                        $fileVar['size'][$i],
                        $i
                    );
                    if(!$success){
                        return false;
                    }
                }
                return true;
            }
            else{
                return $this->_copyFile(
                    $file,
                    $onlyCheck,
                    false,
                    $fileVar['name'],
                    $fileVar['type'],
                    $fileVar['tmp_name'],
                    $fileVar['error'],
                    $fileVar['size']
                );
            }
        }
        return true;
    }
    
    protected function _copyFile(RedMVC\Form\Element\File $file, $onlyCheck, $multiple, $name, $type, $tmp_name, $error, $size, $fileNr = ''){
        if(trim($tmp_name) == ''){
            if($file->isRequired()){                    
                $file->addError($this->getError('FORM_FILE_NO_FILE'));
                return false;
            }
            return true;
		}
        // error
        if($error > 0){
            $file->addError($this->getError('FORM_FILE_UPLOAD_ERROR_'.$error));
            return false;
		}
        $fileAttr   = $file->getFile();
        $success    = true;
        // to large
        if($size > $fileAttr->maxSize){
			$file->addError($this->getError('FORM_FILE_TO_LARGE', round($fileAttr->maxSize/1024/1024, 2)));
            $success = false;
		}
        // type not allowed
        // TODO: check mimetype $fileVar['type']
		$fileArray  = explode('.', $name);
		$fileExt    = strtolower($fileArray[count($fileArray)-1]);
		if(!in_array($fileExt, $fileAttr->allowedArray, true)){
			$file->addError($this->getError('FORM_FILE_TYPE_NOT_ALLOWED', implode('|', $fileAttr->allowedArray)));
            $success = false;
		}
        if(!$success){
            return false;
        }
        if(!$onlyCheck){
            // fileName
            if($fileAttr->fileName == RedMVC\Form\File::FILE_NAME_ORIGINAL){
                $fileName = $name;
                $fileName = substr($fileName, 0, -(strlen($fileExt)+1));
            }
            else if($fileAttr->fileName == RedMVC\Form\File::FILE_NAME_RANDOM){
                $fileName = md5(uniqid(rand(), true));
            }
            else{
                $fileName = $fileAttr->fileName;
            }
            // make folder
            if(!is_dir($fileAttr->targetFolder)){
                mkdir($fileAttr->targetFolder, 0777, true);
            }
            // copy file
            $finalFile = $fileAttr->targetFolder.DIRECTORY_SEPARATOR.$fileName.'.'.$fileExt;
            if(!move_uploaded_file($tmp_name, $finalFile)){
                $file->addError($this->getError('FORM_FILE_COPY_ERROR'));
                return false;
            }
            $file->getFile()->setFinalFile($finalFile);
        }
        return true;
    }
    
    protected function _getTotalSize($sizeArray){
        $totalSize = 0;
        foreach($sizeArray as $size){
            $totalSize += $size;
        }
        return $totalSize;
    }

}